package xyz.lwm.lazycat.netpipe.controller;

import xyz.lwm.lazycat.annotation.Inject;
import xyz.lwm.lazycat.netpipe.domain.entity.ProxyConfig;
import xyz.lwm.lazycat.netpipe.service.ProxyConfigService;
import xyz.lwm.lazycat.utility.Assert;
import xyz.lwm.lazycat.utility.R;
import xyz.lwm.lazycat.utility.StringUtil;
import xyz.lwm.lazycat.web.annocation.Controller;
import xyz.lwm.lazycat.web.annocation.Delete;
import xyz.lwm.lazycat.web.annocation.Get;
import xyz.lwm.lazycat.web.annocation.PathParam;
import xyz.lwm.lazycat.web.annocation.Post;
import xyz.lwm.lazycat.web.annocation.Put;

import java.util.List;

import static xyz.lwm.lazycat.netpipe.util.Constants.ROOT_PATH;

/**
 * 代理配置
 *
 * @author lwm
 */
@Controller(ROOT_PATH)
public class ProxyConfigController {

    @Inject
    private ProxyConfigService proxyConfigService;

    /**
     * 获取代理配置列表
     */
    @Get("configs")
    public R<List<ProxyConfig>> list() {
        return R.ok(proxyConfigService.list());
    }

    /**
     * 获取代理配置
     */
    @Get("configs/{userId}")
    public R<List<ProxyConfig>> list(@PathParam("userId") String userId) {
        return R.ok(proxyConfigService.list(userId));
    }

    /**
     * 添加代理配置
     */
    @Post("configs")
    public R<String> save(ProxyConfig proxyConfig) {
        Assert.isTrue(proxyConfig.getProxyType() > 0, "代理类型错误");
        Assert.isTrue(proxyConfig.getProxyPort() > 0, "代理端口必须大于0");
        Assert.isTrue(proxyConfig.getLocalPort() > 0, "本地端口必须大于0");
        Assert.isTrue(StringUtil.isNotBlank(proxyConfig.getLocalIp()), "本地IP不可为空");
        Assert.isTrue(StringUtil.isNotBlank(proxyConfig.getUserId()), "用户ID不可为空");
        proxyConfigService.save(proxyConfig);
        return R.ok("save successfully");
    }

    /**
     * 修改代理配置
     */
    @Put("configs")
    public R<String> update(ProxyConfig proxyConfig) {
        Assert.isTrue(proxyConfig.getId() != null, "代理配置ID不可为空");
        Assert.isTrue(proxyConfig.getProxyType() > 0, "代理类型错误");
        Assert.isTrue(proxyConfig.getProxyPort() > 0, "代理端口必须大于0");
        Assert.isTrue(proxyConfig.getLocalPort() > 0, "本地端口必须大于0");
        Assert.isTrue(StringUtil.isNotBlank(proxyConfig.getLocalIp()), "本地IP不可为空");
        Assert.isTrue(StringUtil.isNotBlank(proxyConfig.getUserId()), "用户ID不可为空");
        proxyConfigService.updateById(proxyConfig);
        return R.ok("update successfully");
    }

    /**
     * 删除代理配置
     */
    @Delete("configs/{userId}")
    public R<String> delete(@PathParam("userId") String userId) {
        Assert.isTrue(StringUtil.isNotBlank(userId), "代理配置ID不可为空");
        proxyConfigService.removeById(userId);
        return R.ok("delete successfully");
    }

}
